package com.lanou.dllo.vc.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.util.PathUtil;
import com.lanou.dllo.vc.MyApplication;
import com.lanou.dllo.vc.R;
import com.lanou.dllo.vc.adapter.CallBackSmeil;
import com.lanou.dllo.vc.adapter.ChatAdapter;
import com.lanou.dllo.vc.adapter.EmotionAdapter;
import com.lanou.dllo.vc.adapter.GridViewAdapter;
import com.lanou.dllo.vc.dao.MessageDBhelper;
import com.lanou.dllo.vc.greendao.ChatMessage;
import com.lanou.dllo.vc.view.EmotionGridview;
import com.lanou.dllo.vc.view.PasteEditText;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 15/11/23.
 */
public class ChatActivity extends BaseActivity implements View.OnClickListener, View.OnTouchListener, CallBackSmeil {

    private TextView chat_user, speakTv;
    private PasteEditText editText;
    private Button btn_more, btn_send;
    private ListView list;
    private List<ChatMessage> chat_con;
    private ChatAdapter adapter;
    private String name, path, chatCon;
    private MyApplication myApplication;
    private String myname, url;
    private ChatMessage chatMessage;
    private Handler handler;
    private int count = 0, len;
    private LinearLayout ll_face_container, more, btn_press_to_speak, ll_btn_container, container_voice_call;
    private RelativeLayout edittext_layout, recording_container;
    private Button recordingBtn, btn_set_mode_keyboard;
    private File myRecAudioFile, cameraFile;
    private MediaRecorder mediaRecorder;
    private boolean sdCardExit;
    private File myRecAudioDir;// 得到Sd卡path
    private ArrayList<String> recordFiles;
    private ImageView emoImg, mic_image, btn_voice_call, btn_picture;
    private ImageView iv_emoticons_checked;
    private ViewPager vPager;
    private List<View> gridviews;
    private List<String> emolist;
    private EmotionAdapter emoAdapeter;
    private EmotionGridview emo_gridview;
    private GridViewAdapter gridviewAdapter;
    private AnimationDrawable animationDrawable;
    private EMMessage message;
    private MessageDBhelper helper;


    @Override
    protected int getLayout() {
        return R.layout.activity_chat;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        chat_user = (TextView) findViewById(R.id.chat_user);
        if (intent != null) {
            name = intent.getStringExtra("name");
            chat_user.setText(name);
        }
        myApplication = new MyApplication();
        myname = myApplication.getUserName();
        //隐藏软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        editText = (PasteEditText) findViewById(R.id.et_sendmessage);
        btn_more = (Button) findViewById(R.id.btn_more);
        btn_send = (Button) findViewById(R.id.btn_send);
        list = (ListView) findViewById(R.id.list);
        mic_image = (ImageView) findViewById(R.id.mic_image);
        btn_picture = (ImageView) findViewById(R.id.btn_picture);
        btn_picture.setOnClickListener(this);

        ll_btn_container = (LinearLayout) findViewById(R.id.ll_btn_container);
        //表情初始化
        emoImg = (ImageView) findViewById(R.id.iv_emoticons_normal);
        emoImg.setOnClickListener(this);
        iv_emoticons_checked = (ImageView) findViewById(R.id.iv_emoticons_checked);
        iv_emoticons_checked.setOnClickListener(this);
        vPager = (ViewPager) findViewById(R.id.vPager);
        container_voice_call = (LinearLayout) findViewById(R.id.container_voice_call);
        btn_voice_call = (ImageView) findViewById(R.id.btn_voice_call);
        btn_voice_call.setOnClickListener(this);


        //viewpage  初始化数据
        gridviews = new ArrayList<View>();
        //表情list
        emolist = getEmotionList(35);
        View gr1 = getGridChildView(1);
        View gr2 = getGridChildView(2);
        gridviews.add(gr1);
        gridviews.add(gr2);
        emoAdapeter = new EmotionAdapter(gridviews);

        vPager.setAdapter(emoAdapeter);

        edittext_layout = (RelativeLayout) findViewById(R.id.edittext_layout);
        recording_container = (RelativeLayout) findViewById(R.id.recording_container);
        btn_press_to_speak = (LinearLayout) findViewById(R.id.btn_press_to_speak);
        btn_press_to_speak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        btn_press_to_speak.setOnTouchListener(this);
        ll_face_container = (LinearLayout) findViewById(R.id.ll_face_container);
        more = (LinearLayout) findViewById(R.id.more);
        recordingBtn = (Button) findViewById(R.id.btn_set_mode_voice);

        btn_set_mode_keyboard = (Button) findViewById(R.id.btn_set_mode_keyboard);
        speakTv = (TextView) findViewById(R.id.speakTv);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (editText.getText().toString() != null && editText.getText().toString().length() > 0) {
                    btn_more.setVisibility(View.GONE);
                    btn_send.setVisibility(View.VISIBLE);
                } else {
                    btn_more.setVisibility(View.VISIBLE);
                    btn_send.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        btn_send.setOnClickListener(this);

        chat_con = new ArrayList<>();
        adapter = new ChatAdapter(this);
        list.setAdapter(adapter);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                adapter.addData(chat_con);
                return false;
            }
        });

        /* 判断SD Card是否插入 */
        sdCardExit = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
        helper = new MessageDBhelper();
        Log.i("lanou","----->到这了"+MyApplication.getInstance().getUserName());
        chat_con = helper.readMessage(MyApplication.getInstance().getUserName());

        Log.i("lanou","----->看这"+chat_con);
//        Log.i("lanou","----->看这"+helper.readDate(MyApplication.getInstance().getUserName()));
        if (chat_con != null) {
            adapter.addData(chat_con);
        }
    }

    @Override
    protected void initData() {




        //接收消息:
        EMChatManager.getInstance().registerEventListener(new EMEventListener() {

            @Override
            public void onEvent(EMNotifierEvent event) {
                // TODO Auto-generated method stub
                message = (EMMessage) event.getData();
//                ((EMMessage) event.getData()).getBody()这个返回的是文本信息
//                ((EMMessage) event.getData()).getFrom()这个是发送人
//                ((EMMessage) event.getData()).getTo()这个是接收人
                Log.i("lanou", "==========>收到新消息" + event.getData());

                if (String.valueOf(((EMMessage) event.getData()).getFrom()).equals(name)) {

                    chatCon = String.valueOf(((EMMessage) event.getData()).getBody());
                    Log.i("lanou", "----------->保存聊天" + chatCon);
                    Log.i("lanou", "----------->保存聊天" + String.valueOf(((EMMessage) event.getData()).getType()));

                    if (String.valueOf(((EMMessage) event.getData()).getType()).equals("IMAGE")) {
                        String[] str = chatCon.split("thumbnial:");
                        Log.i("lanou", "" + str[str.length - 1]);
                        chatCon = str[str.length - 1];
                    }
                    chatMessage = new ChatMessage();
                    chatMessage.setFromUsre_Con(chatCon);
                    chatMessage.setToUser(name);
                    chat_con.add(chatMessage);
                    helper.saveData(chat_con);
                    handler.sendEmptyMessage(10);


                    Log.i("lanou", "zhejlj_________________");
                } else {
                    Log.i("lanou", "---------asda--->");
                }

            }
        }, new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage});


    }

    /**
     * 点击监听
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send://发送
                send();

                break;
            case R.id.btn_take_picture://拍照功能
                takePicture();
                break;
            case R.id.iv_emoticons_normal:
                //发送表情:
                displayEmo();
                break;
            case R.id.iv_emoticons_checked://表情按钮被点击
                emoImg.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.GONE);
                more.setVisibility(View.GONE);
                break;
            case R.id.btn_voice_call://语音通话
                voiceCall();
                break;
            case R.id.btn_picture://发送照片
                Intent intent = new Intent();
                /* 开启Pictures画面Type设定为image */
                intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
                startActivityForResult(intent, 1);
                break;

        }
    }

    /**
     * 语音通话
     */
    private void voiceCall() {
//        Intent intent = new Intent(ChatActivity.this, VoiceCallActivity.class);
//        intent.putExtra("username", name);
//        intent.putExtra("isComingCall", false);
//        startActivity(intent);
        if (!EMChatManager.getInstance().isConnected()) {
            Toast.makeText(this, "没有连接服务", 0).show();
        } else {
            startActivity(new Intent(this, VoiceCallActivity.class).putExtra("username", name)
                    .putExtra("isComingCall", false));
            // voiceCallBtn.setEnabled(false);
        }

    }

    /**
     * 显示表情
     */
    private void displayEmo() {
        emoImg.setVisibility(View.INVISIBLE);
        ll_btn_container.setVisibility(View.GONE);
        iv_emoticons_checked.setVisibility(View.VISIBLE);
        more.setVisibility(View.VISIBLE);


    }


    private View getGridChildView(int i) {
        View view = View.inflate(this, R.layout.item_emo_gridview, null);
        emo_gridview = (EmotionGridview) view.findViewById(R.id.emo_gridview);
        List<String> list = new ArrayList<String>();
        if (i == 1) {
            List<String> list1 = emolist.subList(0, 20);
            Log.i("lanou", emolist.get(3) + "emotion的第三个图片的名字");
            list.addAll(list1);
        } else if (i == 2) {
            list.addAll(emolist.subList(20, emolist.size()));
        }
        list.add("delete_expression");
        gridviewAdapter = new GridViewAdapter(this, list);
        Log.i("lanou", list + "表情列表");

        emo_gridview.setAdapter(gridviewAdapter);

        gridviewAdapter.setCallBackSmeil(this);

        return view;
    }

    /**
     * 设置表情列表
     *
     * @param emoname
     */
    @Override
    public void getEmotion(String emoname) {
        Log.i("lanou", "表情图片" + emoname);
        String emotions = emoname;
        int resId = getResources().getIdentifier(emotions, "mipmap", getPackageName());
        Bitmap bitmap = null;
        bitmap = BitmapFactory.decodeResource(getResources(), resId);
        ImageSpan imageSpan = new ImageSpan(ChatActivity.this, bitmap);

        SpannableString spannableString =
                new SpannableString(emotions);

        spannableString.setSpan(imageSpan, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (emotions != "delete_expression") {
            editText.append(spannableString);
        }
        if (emotions == "delete_expression" && editText.getText().length() >= 5) {
            String readySend = editText.getText().toString();
            int sendLen = editText.getText().length() - 5;
            if (sendLen >= 5) {
                String send = readySend.substring(0, sendLen);
                int resId_ready = getResources().getIdentifier(send, "mipmap", getPackageName());
                Bitmap bitmap_ready = BitmapFactory.decodeResource(getResources(), resId_ready);
                ImageSpan span = new ImageSpan(ChatActivity.this, bitmap_ready);
                SpannableString string = new SpannableString(send);
                string.setSpan(span, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                editText.setText(string);
                editText.setSelection(editText.getText().length());
            } else if (sendLen == 0) {
                editText.setText("");
            }

        }
    }


    /**
     * 拍照功能
     */
    private void takePicture() {
//        Intent intent = new Intent(this, CamerActivity.class);
//        startActivityForResult(intent, 100);

        cameraFile = new File(PathUtil.getInstance().getImagePath(), myApplication.getInstance().getUserName()
                + System.currentTimeMillis() + ".jpg");
        if (!cameraFile.getParentFile().exists())
            cameraFile.getParentFile().mkdirs();
        url = cameraFile.getAbsolutePath();
        Log.i("lanou", url + "发送图片的文件");
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                18);


        Log.i("lanou00", "Uri------------>" + Uri.fromFile(cameraFile));
    }

    //获取图片的列表
    private List<String> getEmotionList(int getSum) {

        List<String> emotionlist = new ArrayList<>();
        for (int j = 1; j < 10; j++) {
            String imgname = "ee_0" + j;

            emotionlist.add(imgname);
        }
        for (int i = 10; i <= getSum; i++) {

            String imgname = "ee_" + i;

            emotionlist.add(imgname);
        }
        return emotionlist;


    }

    /**
     * 发送
     */
    private void send() {
        String charString = editText.getText().toString();
        if (charString != null) {
//                    chat_con.add(charString);
            editText.setText("");

            chatMessage = new ChatMessage();
            chatMessage.setToUsre_Con(charString);
            chatMessage.setFromUser(MyApplication.getInstance().getUserName());
            Log.i("lanou", Thread.currentThread().getId() + "----3213--->" + chatMessage);
            Log.i("lanou", "----->看这2" + chat_con);
            if (chat_con == null || chat_con.size() == 0) {
                chat_con = new ArrayList<>();
            }
            chat_con.add(chatMessage);
            Log.i("lanou", chat_con + "____.");
            adapter.addData(chat_con);
            helper.saveData(chat_con);

            ////添加到服务器

            EMConversation conversation = EMChatManager.getInstance().getConversation(myname);
            Log.i("lanou", myname + "LLLLLL");
            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
            TextMessageBody txtBody = new TextMessageBody(charString);
            message.addBody(txtBody);

            message.setReceipt(name);
            conversation.addMessage(message);
            EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                @Override
                public void onSuccess() {
                    Log.i("lanou", "发送成功");
                }

                @Override
                public void onError(int i, String s) {
                    Log.i("lanou", "发送失败");
                }

                @Override
                public void onProgress(int i, String s) {

                }
            });


        }
    }

    /**
     * 加号展示更多内容的点击判断
     *
     * @param view
     */
    public void toggleMore(View view) {

        if (count % 2 == 0) {

            more.setVisibility(View.VISIBLE);
            ll_btn_container.setVisibility(View.VISIBLE);
            ll_face_container.setVisibility(View.GONE);
        } else {
            more.setVisibility(View.GONE);
            ll_face_container.setVisibility(View.VISIBLE);
        }
        count++;

    }

    /**
     * 发语音按钮
     */
    public void setModeVoice(View view) {
        more.setVisibility(View.GONE);
        btn_press_to_speak.setVisibility(View.VISIBLE);
        edittext_layout.setVisibility(View.GONE);
        btn_set_mode_keyboard.setVisibility(View.VISIBLE);
        recordingBtn.setVisibility(View.GONE);

    }


    /**
     * 录音初始化
     *
     * @throws IOException
     */
    private void initializeAudio() throws IOException {
        {
            try {
                if (!sdCardExit) {
                    Toast.makeText(ChatActivity.this, "请插入SD Card", Toast.LENGTH_LONG).show();
                    return;
                }
                myRecAudioFile = new File(PathUtil.getInstance().getVoicePath(), myApplication.getInstance().getUserName()
                        + System.currentTimeMillis() + ".mp3");
                if (!myRecAudioFile.getParentFile().exists())
                    myRecAudioFile.getParentFile().mkdirs();


                mediaRecorder = new MediaRecorder();
                    /* 设置录音来源为麦克风 */
                mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);//文件保存位置
                mediaRecorder.setOutputFile(myRecAudioFile.getAbsolutePath());
                mediaRecorder.prepare();
                mediaRecorder.start();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.btn_press_to_speak) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                Log.i("lanou", "点击－－－－－－－－－－》");
                speakTv.setText("按住录音");
//                speakTv.setBackgroundResource(android.R.color.holo_red_light);
                recording_container.setVisibility(View.INVISIBLE);
                animationDrawable = (AnimationDrawable) mic_image.getDrawable();
                animationDrawable.stop();
                if (myRecAudioFile != null) {
                    /* 停止录音 */
                    mediaRecorder.stop();
                    mediaRecorder.release();
                    mediaRecorder = null;
                }
                chatMessage = new ChatMessage();
                chatMessage.setToUsre_Con(myRecAudioFile.getAbsolutePath());
                chat_con.add(chatMessage);
                adapter.addData(chat_con);
                message = null;

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        EMConversation conversation = EMChatManager.getInstance().getConversation(name);
                        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.VOICE);
                        FileInputStream fis = null;
                        try {
                            fis = new FileInputStream(myRecAudioFile.getAbsolutePath());
                            len = fis.available();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        Log.i("lanou", "voice发送-------" + myRecAudioFile.getAbsolutePath());
                        VoiceMessageBody body = new VoiceMessageBody(new File(myRecAudioFile.getAbsolutePath()), len);
                        message.addBody(body);
                        message.setReceipt(name);
                        conversation.addMessage(message);


                        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                Log.i("lanou", "-------voice------->发送成功");
                            }

                            @Override
                            public void onError(int i, String s) {
                                Log.i("lanou", "-------voice------->发送失败");
                            }

                            @Override
                            public void onProgress(int i, String s) {

                            }
                        });
                    }
                }).start();

            }
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                speakTv.setText("松手结束");

                recording_container.setVisibility(View.VISIBLE);
                mic_image.setImageResource(R.drawable.record_animation);
                animationDrawable = (AnimationDrawable) mic_image.getDrawable();
                animationDrawable.start();
//                speakTv.setBackgroundResource(android.R.color.holo_red_dark);
                if (myRecAudioFile != null) {
                    /* 停止录音 */
                    myRecAudioFile = null;
                }
                try {
                    initializeAudio();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return false;
    }

    /**
     * 弹软键盘
     *
     * @param view
     */
    public void setModeKeyboard(View view) {
        more.setVisibility(View.GONE);

        btn_press_to_speak.setVisibility(View.GONE);
        edittext_layout.setVisibility(View.VISIBLE);
        btn_set_mode_keyboard.setVisibility(View.GONE);
        recordingBtn.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == 18) { // 拍照发送照片

            sendPicture(cameraFile.getAbsolutePath());
            chatMessage = new ChatMessage();
            chatMessage.setToUsre_Con(cameraFile.getAbsolutePath());
            chat_con.add(chatMessage);
            Log.i("lanou", chat_con + "____.------>");
            adapter.addData(chat_con);

        }

        //发送地图
        else if (requestCode == 19) {

            if (data!=null) {
                String address = data.getStringExtra("mylocation");
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude", 0);

                Log.i("lanou0000", address + latitude + longitude);
                if (address != null && address.length() > 0) {
                    sendMyLocation(address, longitude, longitude);
                }
            }

        }

        ContentResolver resolver = getContentResolver();

        //此处的用于判断接收的Activity是不是你想要的那个

        if (requestCode == 1) {


            Uri originalUri = data.getData();        //获得图片的uri

//                Bitmap bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);        //显得到bitmap图片

            //获取图片的路径：

            String[] proj = {MediaStore.Images.Media.DATA};

            //好像是android多媒体数据库的封装接口，具体的看Android文档

            Cursor cursor = managedQuery(originalUri, proj, null, null, null);

            //按我个人理解 这个是获得用户选择的图片的索引值

            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

            //将光标移至开头 ，这个很重要，不小心很容易引起越界

            cursor.moveToFirst();

            //最后根据索引值获取图片路径

            String path = cursor.getString(column_index);
            Log.i("lanou", "path------>>>" + path);


            chatMessage = new ChatMessage();
            chatMessage.setToUsre_Con(path);
            chat_con.add(chatMessage);
            adapter.addData(chat_con);

        }


    }

    private void sendPicture(final String filePath) {
        EMConversation conversation = EMChatManager.getInstance().getConversation(name);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE);
        //如果是群聊，设置chattype,默认是单聊
//        message.setChatType(EMMessage.ChatType.GroupChat);

        ImageMessageBody body = new ImageMessageBody(new File(filePath));
        // 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
        // body.setSendOriginalImage(true);
        message.addBody(body);
        message.setReceipt(name);
        conversation.addMessage(message);
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("lanou", "发送成功");
            }

            @Override
            public void onError(int i, String s) {
                Log.i("lanou", "发送失败");
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });

        setResult(RESULT_OK);
    }


    //点击获取地址的按钮监听

    public void location_onClick(View view) {

        Intent intent = new Intent(ChatActivity.this, ShowMapActivity.class);

        startActivityForResult(intent, 19);
    }

    private void sendMyLocation(String location, double latitude, double longitude) {
        EMConversation conversation = EMChatManager.getInstance().getConversation(name);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.LOCATION);
//        ImageMessageBody body = new ImageMessageBody();
        LocationMessageBody body = new LocationMessageBody(location, latitude, longitude);
        //默认超过100k的图片会压缩,发给对方,可以设置成发送原图
        message.addBody(body);
        message.setReceipt(name);
        conversation.addMessage(message);

        chatMessage = new ChatMessage();
        chatMessage.setToUsre_Con("location:" + location);
        chat_con.add(chatMessage);
        adapter.addData(chat_con);

        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("mymap", "发送成功了我的地址");
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });

        setResult(RESULT_OK);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

